import os
import pathlib
import sys

project_path = str(pathlib.Path(os.path.dirname(__file__)).parent.parent)
sys.path.append(project_path)
from utility.import_log import flog
shell = __import__("shell.import.es_import", globals(), locals(), ['col2es','file2es'], 0)

"""
格式：
导入企业表201712月份值数据
python import_to_es_by_python.py value t0202_kgem_test 201712 /home/datafile.dat seq action
导入表字段结构
python import_to_es_by_python.py struct 'none' 'none' 'none' 'none' 'none'
"""

params = sys.argv
ntype, name, month, datafile, sep, action = str.lower(params[1]), str.lower(params[2]), \
                                            params[3], params[4], params[5], params[6]
logger =flog(params[3],__file__)
logger.info(f"""===【接收到参数 ntype:{ntype},name:{name},month:{month},datafile:{datafile},
                          sep:{sep},action:{action}程序启动!】===""")
try:

    if ntype not in ['value', 'struct']:
        raise ValueError(f"{ntype}类型参数指定错误")

    if action not in ['init','add','add_update','del']:
        raise ValueError(f"{action}类型参数指定错误或者不支持")

except Exception as e:
    logger.error(f'===【{str(e)}】===')
    logger.error("""===【传入参数有误，格式例子如下：
        导入企业表201712月份值数据
        python import_to_es_by_python.py value t0202_kgem_test 201712 数据文件地址 分隔符 增量或者新增
        导入表字段结构
        python import_to_es_by_python.py struct 'none' 'none' 'none' 'none' 'none'】===
        """)
    sys.exit(1)


if ntype == 'value':
    ntype, name, month, datafile, sep, action = str.lower(params[1]), str.lower(params[2]), \
                                                params[3][0:6], params[4], params[5], str.lower(params[6])
    if not os.path.isfile(datafile):
        raise FileExistsError(f"{datafile}数据文件不存在")
    try:
        if action in ["add"]:
            shell.file2es(name, month, datafile, sep, action)
        else:
            logger.error("不支持的action参数")
            sys.exit(1)
    except Exception as e:
        logger.error(f'===【{str(e)}】===')
        logger.error(f"""===【导入列值执行失败,执行参数：ntype:{ntype},name:{name},month:{month},datafile:{datafile},
                              sep:{sep},action:{action}】===""")
        sys.exit(1)

if ntype == 'struct':

    try:
        if action in ['add']:
            shell.col2es(action=action)
        else:
            logger.error("不支持的action参数")
    except Exception as e:
        logger.error(str(e))
        logger.error(f"""===【导入列名执行失败,执行参数：ntype:{ntype},name:{name},month:{month},datafile:{datafile},
                              sep:{sep},action:{action}】===""")
        sys.exit(1)

logger.info(f"""===【命令执行完成,执行参数：ntype:{ntype},name:{name},month:{month},datafile:{datafile},
                              sep:{sep},action:{action}】===""")
sys.exit(0)
